package com.demo.lambda;

import java.util.concurrent.RecursiveTask;

/**
 * @author XuYang
 * @since 2025/2/24 14:30
 */
public class SumTask
    extends RecursiveTask<Integer>
{
    /**
     * 定义任务拆分的临界值
     */
    private static final int THRESHOLD = 10;
    private final int[] array;
    private final int start;
    private final int end;

    SumTask(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        // 如果任务足够小，直接计算
        if ((end - start) <= THRESHOLD) {
            int sum = 0;
            for (int i = start; i < end; i++) {
                sum += array[i];
            }
            return sum;
        }
        // 否则，分解任务
        else {
            int middle = (start + end) / 2;
            SumTask leftTask = new SumTask(array, start, middle);
            SumTask rightTask = new SumTask(array, middle, end);

            // 异步执行左边的任务
            leftTask.fork();
            // 同步执行右边的任务
            int rightResult = rightTask.compute();
            // 右边任务执行完成后, 会加入窃取其他线程队列中任务进行执行
            int leftResult = leftTask.join();

            return leftResult + rightResult;
        }
    }
}
